import math
from array import array
import reprlib


class Vector:
    typecode = 'd'

    def __init__(self, components):
        self._components = array(self.typecode, components)

    def __iter__(self):
        # 迭代
        return iter(self._components)

    def __repr__(self):
        components = reprlib.repr(self._components)  # array('d', [1, 2, 3, 4, 5, ...])
        components = components[components.find('['):-1]  # [1, 2, 3, 4, 5, ...]
        return 'Vector({})'.format(components)

    def __str__(self):
        return str(tuple(self))

    def __bytes__(self):
        return bytes(ord(self.typecode)) + bytes(self._components)

    def __eq__(self, other):
        return tuple(self) == tuple(other)

    def __abs__(self):
        return math.sqrt(sum(x * x for x in self))

    def __bool__(self):
        return bool(abs(self))

    @classmethod
    def frombytes(cls, octets):
        typecode = chr(octets[0])
        memv = memoryview(octets[1:]).cast(typecode)
        return cls(memv)


if __name__ == '__main__':
    arr = array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    a = reprlib.repr(arr)
    print(a)
    print(a.find('['))
    print(a[a.find('['):-1])
    print(bytes([ord('d')]) + bytes(arr))
    v = Vector([3.0, 4.0])
    print(tuple(v))
    print(v)
